const https = require("https");
const http = require("http");
const qs=require('querystring');
const config=require('./config')();
var data="";
var fs=require('fs')
function callback(e, r) {
    if (e) {
        console.log('[sql ERROR] - ', e.message);
        return;
    }

}

var sql="INSERT INTO city (id,name,pinyin,isOpen) VALUES(?,?,?,?)";
function addCity(item) {
    config.mysql.query(sql,
        [item.id,item.name,item.pinyin,item.isOpen],
        callback);
}

function addCategory(cityid) {
    let sql1="INSERT INTO goodsCategory (id,`name`,city_id) VALUES(?,?,?)";
    let data1="";
    let content=qs.stringify({

    });
    let req1=http.request(
        config.urls.categoryList,
        {
            method:'POST',
            headers:{
                'Content-Type':'application/json',
                //'Content-Length':
                'Cookie':'ci='+cityid
            }
        },
        function (res) {
            res.setEncoding('utf-8');
            res.on('data', function (chunk) {
                data1 += chunk;
            });
            res.on('end',function () {
                data1=JSON.parse(data1).data;
                data1.categoryList.forEach(function (item, index) {
                    config.mysql.query(sql1,[item.id,item.name,cityid],callback);
                });
            })
        });
    req1.on("error", function (e) {
        console.error(`${req1.path}: ${e.message}`);
    });
    req1.write(content);
    req1.end();
}

function addSubway(cityid) {
    let url=config.urls.subwayList.substring(0,config.urls.subwayList.indexOf('=')+1)+cityid;
    let sql1="INSERT INTO subway (id,`name`,city_id) VALUES(?,?,?)";
    let sql2="INSERT INTO station (id,`name`,lat,`long`,city_id,line_id,pinyin) VALUES(?,?,?,?,?,?,?)";
    let data1="";
    let req1=https.request(
        url,
        {
            method:'GET'
        },
        function (res) {
            res.setEncoding('utf-8');
            res.on('data', function (chunk) {
                data1 += chunk;
            });
            res.on('end',function () {
                let data2=JSON.parse(data1).data;
                if(!data2) return;
                //console.log(data2);
                data2.forEach(function (item, index) {
                    config.mysql.query(sql1,[item.lineId,item.name,cityid],callback);
                    item.stations.forEach(function (item1, index1) {
                        config.mysql.query(sql2,[item1.id,item1.name,item1.latitude/1000000,item1.longitude/1000000,cityid,item.lineId,item1.pinyin],callback);
                    })
                });
            })
        });
    req1.on("error", function (e) {
        console.error(`${req1.path}: ${e.message}`);
    });
    req1.end();
    console.log(url);
}

function addArea(cityid) {
    let url=config.urls.areaList.substring(0,config.urls.areaList.indexOf('=')+1)+cityid;
    let sql1="INSERT INTO district (id,`name`,city_id,slug,type) VALUES(?,?,?,?,?)";
    let sql2="INSERT INTO area (id,`name`,city_id,slug,district_id,status,type,isHot,isLandMark) VALUES(?,?,?,?,?,?,?,?,?)";
    let data1="";
    let req1=https.request(
        url,
        {
            method:'GET'
        },
        function (res) {
            res.setEncoding('utf-8');
            res.on('data', function (chunk) {
                data1 += chunk;
            });
            res.on('end',function () {
                let data2=JSON.parse(data1).data;
                if(!data2) return;
                if(data2.areasinfo){
                    data2.areasinfo.forEach(function (item1, index1) {
                        config.mysql.query(sql1,[item1.id,item1.name,cityid,item1.slug,item1.type],callback);
                    });
                }
                if(data2.bizArea){
                    data2.bizArea.forEach(function (item2, index2) {
                        config.mysql.query(sql2,[item2.id,item2.name,cityid,item2.slug,item2.district,null,item2.type,0,0],callback);
                    });
                }
                if(data2.landmarks){
                    data2.landmarks.forEach(function (item2, index2) {
                        config.mysql.query(sql2,[item2.id,item2.name,cityid,item2.slug,null,item2.status,item2.type,0,1],callback);
                    });
                }
                if(data2.subareasinfo){
                    data2.subareasinfo.forEach(function (item2, index2) {
                        config.mysql.query(sql2,[item2.id,item2.name,cityid,item2.slug,item2.district,null,item2.type,0,0],callback);
                    });
                }
                if(data2.hotlandmarks){
                    data2.hotlandmarks.forEach(function (item2, index2) {
                        config.mysql.query("UPDATE area SET isHot=1 where id=?",[item2.id],callback);
                    });
                }
            })
        });
    req1.on("error", function (e) {
        console.error(`${req1.path}: ${e.message}`);
    });
    req1.end();
    console.log(url);
}

async function addStore(cityid){
    let sql1="INSERT INTO store (poi_id,`name`,avgPrice,avgScore,areaName,cateName,frontImg,lat,lng,channel,smartTags,extraServiceTags,rotationTags,poiImgExtra,preferentialInfo,city_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    for(let i=0;i<20;i++){
        let data1="";
        let content=qs.stringify({
            offset:50*i,
            limit:50,
            cateId:1,
            lineId:0,
            areaId:0,
            stationId:0,
            solds:'default'
        });
        let req1=await http.request(
            config.urls.storeList,
            {
                method:'POST',
                headers:{
                    'Cookie':'ci='+cityid+';uuid=01a9b629-56ec-493c-9040-6647ecc37a61;client-id=382e435b-7392-4ff9-8497-e4560324d185',
                }
            },
            function (res) {
                res.setEncoding('utf-8');
                res.on('data', function (chunk) {
                    data1 += chunk;
                });
                res.on('end',function () {
                    //console.log(data1);
                    data1=JSON.parse(data1).data;
                    if(!data1) return;
                    if(!data1.poiList) return;
                    console.log('cityId:'+cityid+' offset:'+50*i+' poiInfos:'+data1.poiList.poiInfos.length);
                    data1.poiList.poiInfos.forEach(function (item, index) {
                        config.mysql.query(sql1,[item.poiid,item.name,item.avgPrice,item.avgScore,item.areaName,item.cateName,item.frontImg,item.lat,item.lng,item.channel,JSON.stringify(item.smartTags?item.smartTags:{}),JSON.stringify(item.extraServiceTags),JSON.stringify(item.rotationTags),JSON.stringify(item.poiImgExtra),JSON.stringify(item.preferentialInfo),cityid],callback);
                        addDeal(item.poiid);
                    });
                })
            });
        req1.on("error", function (e) {
            //console.error(`${req1.path}: ${e.message}`);
        });
        req1.write(content);
        req1.end();

    }

}

async function addDeal(poiid) {
    let sql2="INSERT INTO deal (id,title,imgUrl,price,originPrice,campaignTag,solds,taglist,store_id,attr) VALUES(?,?,?,?,?,?,?,?,?,?)";
    let data2="";
    let content2=qs.stringify({
        poiId:poiid,

    });
    let req1=await http.request(
        config.urls.dealList,
        {
            method:'POST',
            headers:{
                'Cookie':'uuid=01a9b629-56ec-493c-9040-6647ecc37a61;client-id=382e435b-7392-4ff9-8497-e4560324d185',
                "Content-Type": "application/x-www-form-urlencoded",
                'Content-Length': Buffer.byteLength(content2),
                'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'
            }
        },
        function (res) {
            res.setEncoding('utf-8');
            res.on('data', function (chunk) {
                data2 += chunk;
            });
            res.on('end',function () {
                data2=JSON.parse(data2).data;
                if(!data2) return;
                console.log('poiid:'+poiid+' voucherArr:'+data2.voucherArr.length+' dealArr:'+data2.dealArr.length);
                if(data2.voucherArr){
                    data2.voucherArr.forEach(function (item, index) {
                        config.mysql.query(sql2,[item.dealId,item.title,item.imgUrl,item.price,item.originPrice,item.campaignTag,item.solds,JSON.stringify(item.taglist),poiid,'voucher'],callback);
                    });
                }
                if(data2.dealArr){
                    data2.dealArr.forEach(function (item, index) {
                        config.mysql.query(sql2,[item.dealId,item.title,item.imgUrl,item.price,item.originPrice,item.campaignTag,item.solds,JSON.stringify(item.taglist),poiid,'deal'],callback);
                    });
                }
            })
        });
    req1.on("error", function (e) {
        //console.error(`${req1.path}: ${e.message}`);
    });
    req1.write(content2);
    req1.end();
    //console.log('poiid:'+poiid);
}


function reqCity() {
    var req = https.request(
        config.urls.cityList,
        {
            method:"GET"
        },
        function (res) {
            res.setEncoding('utf-8');
            res.on('data', function (chunk) {
                data += chunk;
            });
            res.on('end',function () {
                data=JSON.parse(data).data;
                data.forEach(function (item, index) {
                    //addCity(item);
                    //addSubway(item.id);
                    //addArea(item.id);
                    //addCategory(item.id);
                    addStore(item.id);
                });
            })
        });

    req.on("error", function (e) {
        //console.error(`${req.path}: ${e.message}`);
    });
    req.end();
}

//reqCity();
addStore(10);